package com.newear.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.util.ArrayMap;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.newear.MyApplication;
import com.newear.R;
import com.newear.base.ui.circlecamera.CameraListener;
import com.newear.base.ui.circlecamera.CameraPreview;
import com.newear.base.ui.circlecamera.OvalCameraLayout;
import com.newear.bean.CustomerInfo;
import com.newear.constant.DataType;
import com.newear.constant.RequireParams;
import com.newear.happyDialog.CamaraCheckDialog;
import com.newear.message.MessageDispatcher;
import com.newear.message.MessageType;
import com.newear.util.MyLogger;
import com.newear.util.MyMediaPlayer;
import com.newear.util.ProgressDialogUtil;
import com.newear.util.Validator;

import java.lang.ref.WeakReference;

/**
 * 面诊
 */
public class FaceActivity extends AppCompatActivity {
    private static final String TAG = "FaceActivity";
    private ImageView ivClose;
    private OvalCameraLayout rootLayout;
    private CameraPreview cameraPreview;
    private LinearLayout ll;
    private MediaPlayer mediaPlayer;
    private String key;
    private MyHandler myHandler;
    private ProgressDialog mProgressDialog; //网络请求时用的进度条
    private Context mContext;
    private boolean resume = false;//解决home键黑屏问题

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_face);
        init();
        findViews();
        setListeners();
    }

    private void init() {
        this.key = this.hashCode() + "";
        this.mContext = this;
        myHandler = new MyHandler(this);
        mProgressDialog = ProgressDialogUtil.getProgressDialog(mContext);
        MyApplication.sCustomerInfo = new CustomerInfo();
        //mediaPlayer = MyMediaPlayer.getInstance().playing(this, "raw/face.mp3");
        mediaPlayer = MyMediaPlayer.getInstance().playing2(this, R.raw.face);
    }

    private void findViews() {
        ivClose = (ImageView) findViewById(R.id.iv_close);
        ll = (LinearLayout) findViewById(R.id.ll);
        rootLayout = (OvalCameraLayout) findViewById(R.id.rootLayout);
    }

    private void setListeners() {
        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null == cameraPreview) return;
                if (MyApplication.sCustomerInfo.faceBitmap == null) {
                    cameraPreview.captureImage();//抓取照片
                } else {
                    uploadFaceBitmap();
                }
            }
        });

        ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FaceActivity.this.finish();
            }
        });
    }

    private void startCamera() {
        if (null != cameraPreview) cameraPreview.releaseCamera();
        cameraPreview = new CameraPreview(this, CameraPreview.Type.FACE);
        cameraPreview.post(new Runnable() {
            @Override
            public void run() {
                MyLogger.e("josan", "cameraPreview height:" + cameraPreview.getHeight() + ",width:" + cameraPreview.getWidth() + ",ratio:" + ((cameraPreview.getWidth()*1.0) / cameraPreview.getHeight()));
            }
        });
        rootLayout.removeAllViews();
        rootLayout.setCameraPreview(cameraPreview);
        if (resume) {
            rootLayout.startView();
        }
        cameraPreview.setCameraListener(new CameraListener() {
            @Override
            public void onCaptured(Bitmap bitmap) {
                if (null != bitmap) {
                    // 拿到bitmap
                    MyApplication.sCustomerInfo.faceBitmap = bitmap;
                    View view = rootLayout.getOvalView();
                    if (view != null) {
                        view.setBackgroundDrawable(new BitmapDrawable(bitmap));
                    }
                } else {
                    Toast.makeText(FaceActivity.this, "拍照失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    /**
     * 上传照片
     */
    private void uploadFaceBitmap() {
        ArrayMap<String, Object> param = new ArrayMap<String, Object>();
        param.put(RequireParams.DATA_TYPE, DataType.UPLOAD_FACE_PHOTO);
        param.put(RequireParams.MAP_KEY, this.key + DataType.UPLOAD_FACE_PHOTO);
        param.put(RequireParams.CALL_BACK_HANDLER, myHandler);
        MessageDispatcher.sendMessage(MyApplication.getHandler(), MessageType.REQUIRE_DATA, param);
    }


    @Override
    protected void onResume() {
        super.onResume();
        startCamera();
        resume = true;
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
            mediaPlayer.release();
        }
        mediaPlayer = null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != cameraPreview) {
            cameraPreview.releaseCamera();
        }
        rootLayout.release();
    }

    private void sucessAlert(){

    }

    static class MyHandler extends Handler {
        WeakReference<Activity> mActivityReference;

        MyHandler(Activity mActivity) {
            mActivityReference = new WeakReference<Activity>(mActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            try {
                final FaceActivity activity = (FaceActivity) mActivityReference.get();
                if (activity != null) {
                    super.handleMessage(msg);
                    switch (msg.what) {
                        case MessageType.SHOW_DIALOG:   //显示对话框
                            if (activity.mProgressDialog != null) {
                                activity.mProgressDialog.setMessage(activity.getResources().getString(R.string.upload_face_photo));
                                activity.mProgressDialog.show();
                            }
                            break;
                        case MessageType.CLOSE_DIALOG:  //关闭对话框
                            if (activity.mProgressDialog != null) {
                                activity.mProgressDialog.dismiss();
                            }
                            break;
                        case MessageType.REQUIRE_DATA_FINISHED: //请求数据完成
                            if (msg.arg1 == DataType.UPLOAD_FACE_PHOTO) {
                                SparseArray<String> result = (SparseArray<String>) msg.obj;
                                String errno = result.get(0);
                                if ("1".equals(errno)) {
                                    String faceId = result.get(1);
                                    if (Validator.isEffective(faceId)) {
                                        MyApplication.sCustomerInfo.faceId = faceId;
                                        Log.e(TAG, "脸部照片上传成功，faceId:" + faceId);
                                        //此处弹出成功的框
                                        CamaraCheckDialog camaraCheckDialog = new CamaraCheckDialog(activity, R.style.dialog, "", "面诊照片上传成功!", 5);
                                        camaraCheckDialog.setOnTakePhotoClickListener(new CamaraCheckDialog.OnTakePhotoClickListener() {
                                            @Override
                                            public void takePhotoClickListener() {
                                                activity.finish();
                                            }
                                        });
                                        camaraCheckDialog.show();

                                    }
                                } else if ("0".equals(errno)){
                                    // 没有检测到人脸
                                    CamaraCheckDialog camaraCheckDialog = new CamaraCheckDialog(activity, R.style.dialog, "未检测到人脸", "请重新拍照", CamaraCheckDialog.Type.CAMRA_FACE);
                                    camaraCheckDialog.setOnTakePhotoClickListener(new CamaraCheckDialog.OnTakePhotoClickListener() {
                                        @Override
                                        public void takePhotoClickListener() {
                                            MyApplication.sCustomerInfo.faceBitmap = null;
                                            activity.startCamera();
                                            View view = activity.rootLayout.getOvalView();
                                            if (view != null) {
                                                view.setBackgroundDrawable(null);
                                            }
                                        }
                                    });
                                    camaraCheckDialog.show();
                                }
                            }
                            break;
                        default:
                            break;
                    }
                }
            } catch (Exception e) {
                MyLogger.e(TAG, "handleMessage Exception!e:" + e.getMessage());
            }
        }
    }
}
